# -*- coding: utf-8 -*-
import json
import time

import uuid
from django.urls import reverse
from cent import Client as CentClient, CentException, generate_token
from rest_framework import status
from rest_framework.response import Response
from rest_framework.exceptions import ParseError, ValidationError

import logging
logger = logging.getLogger('bt_server')

from app.models import BtResource
from base.settings import WEBSOCKET_SERVER_URL, WEBSOCKET_SECRET, WEBSOCKET_SERVER_TIME_OUT, WEBSOCKET_CHANNLE, WEBSOCKET_CLIENT_URL, TORRENT_SUFFIX
from common.base_resful_view import BaseResfulView, QueryParameterNotPresentError


cent_client = CentClient(WEBSOCKET_SERVER_URL, WEBSOCKET_SECRET, WEBSOCKET_SERVER_TIME_OUT)


class WebSocketTokenView(BaseResfulView):

    def get(self, request, *args, **kwargs):
        """获取websocket 信息"""

        user = 'browser-{}'.format(uuid.uuid4().hex)
        timestamp = str(int(time.time()))
        info = json.dumps({'client': 'browser', 'name': 'webbt'})
        token = generate_token(WEBSOCKET_SECRET, user, timestamp, info=info)

        return Response({
            'user': user,
            'url': WEBSOCKET_CLIENT_URL,
            'timestamp': timestamp,
            'token': token,
            'info': info,
            'channel': WEBSOCKET_CHANNLE
        }, status=status.HTTP_200_OK)


class NotifyClientDonwloadResourceView(BaseResfulView):

    def post(self, request, *args, **kwargs):
        """通知客户端下载资源"""

        resource_id = self.get_data_parameter('resource_id', value_type=int)
        users = self.get_data_parameter('users', value_type=list)

        try:
            resource = BtResource.objects.get(pk=resource_id)
        except BtResource.DoesNotExist:
            raise ParseError({'codemsg': '参数错误: 不存在的资源id:{}'.format(resource_id)})

        channels = []
        for user in users:
            channels.append('{}:{}'.format(WEBSOCKET_CHANNLE, user))

        root_url = request.build_absolute_uri()

        try:
            cent_client.broadcast(channels, {
                'msg_type': 'DOWNLOAD_RESOURCE',
                'torrent_file_path': request.build_absolute_uri(reverse('torrent_files_direct_download', kwargs={'category': resource.category, 'file_name': resource.torrent_file_name})),
                'file_path': request.build_absolute_uri(reverse('resources_direct_download', kwargs={'category': resource.category, 'file_name': resource.name})),
                'torrent_file_name': resource.torrent_file_name,
                'file_name': resource.name,
                'category': resource.category
            })
        except CentException as e:
            logger.warn(e)
            return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        return Response(status=status.HTTP_201_CREATED)
